const { RegexActionParser } = require('../out/utils/regexActionParser');
const path = require('path');
const fs = require('fs');

// Create test store files for validation
const testStoreModule = `
// Test store module with various action patterns
export default {
  namespaced: true,
  state: {
    data: []
  },
  mutations: {
    SET_DATA(state, data) {
      state.data = data;
    }
  },
  actions: {
    // Method declaration pattern
    async fetchData({ commit }, params) {
      const data = await api.getData(params);
      commit('SET_DATA', data);
    },
    
    // Function expression pattern
    updateData: function({ commit }, payload) {
      commit('SET_DATA', payload);
    },
    
    // Arrow function pattern
    deleteData: ({ commit }, id) => {
      commit('REMOVE_DATA', id);
    },
    
    // Shorthand property assignment
    refreshData,
    
    // Another method
    processData() {
      console.log('processing data');
    },
    
    // Spread assignment for base actions
    ...baseActions,
    
    // Commented out action (should be ignored)
    // disabledAction() { return false; }
  }
}

// This function should not affect action extraction
function refreshData() {
  return { type: 'refresh' };
}
`;

const testRootStore = `
import { createStore } from 'vuex';

const store = createStore({
  state: {
    user: null
  },
  mutations: {
    SET_USER(state, user) {
      state.user = user;
    }
  },
  actions: {
    // Root store actions
    login({ commit }, credentials) {
      // Login logic
      commit('SET_USER', credentials.user);
    },
    
    logout: function({ commit }) {
      commit('SET_USER', null);
    },
    
    // Shorthand
    refreshUser,
    
    // Spread assignment
    ...baseActions
  },
  modules: {
    // modules here
  }
});

function refreshUser() {
  return { type: 'refresh_user' };
}

export default store;
`;

// Write test files
const testDir = path.join(__dirname, '../tests/parser-validation');
if (!fs.existsSync(testDir)) {
  fs.mkdirSync(testDir, { recursive: true });
}

fs.writeFileSync(path.join(testDir, 'test-module.js'), testStoreModule);
fs.writeFileSync(path.join(testDir, 'test-root-store.js'), testRootStore);

// Test the regex parser with custom innerActions
console.log('=== Testing Regex Action Parser with Custom Configuration ===\n');

// Test with custom innerActions
const customInnerActions = ['customAction1', 'customAction2', 'customAction3'];

// Test module parsing with custom innerActions
console.log('1. Testing Module Action Extraction with Custom innerActions:');
const moduleActionsCustom = RegexActionParser.getModuleActionNames(
  path.join(testDir, 'test-module.js'),
  'testModule',
  customInnerActions
);
console.log('Expected custom actions: testModule/customAction1, testModule/customAction2, testModule/customAction3');
console.log('Extracted actions with custom innerActions:', moduleActionsCustom);
console.log('Count:', moduleActionsCustom.length);
console.log('');

// Test module parsing with default innerActions
console.log('2. Testing Module Action Extraction with Default innerActions:');
const moduleActions = RegexActionParser.getModuleActionNames(
  path.join(testDir, 'test-module.js'),
  'testModule'
);
console.log('Expected actions: testModule/fetchData, testModule/updateData, testModule/deleteData, testModule/refreshData, testModule/processData, testModule/setObject, testModule/setData, etc.');
console.log('Extracted actions with default innerActions:', moduleActions);
console.log('Count:', moduleActions.length);
console.log('');

// Test root store parsing with custom innerActions
console.log('3. Testing Root Store Action Extraction with Custom innerActions:');
const rootActionsCustom = RegexActionParser.getRootActionNames(
  path.join(testDir, 'test-root-store.js'),
  customInnerActions
);
console.log('Expected custom actions: login, logout, refreshUser, customAction1, customAction2, customAction3');
console.log('Extracted actions with custom innerActions:', rootActionsCustom);
console.log('Count:', rootActionsCustom.length);
console.log('');

// Test root store parsing with default innerActions
console.log('4. Testing Root Store Action Extraction with Default innerActions:');
const rootActions = RegexActionParser.getRootActionNames(
  path.join(testDir, 'test-root-store.js')
);
console.log('Expected actions: login, logout, refreshUser, setObject, setData, etc.');
console.log('Extracted actions with default innerActions:', rootActions);
console.log('Count:', rootActions.length);
console.log('');

// Validation
console.log('=== Validation Results ===\n');

// Check if key actions are found in default configuration
const expectedModuleActions = ['fetchData', 'updateData', 'deleteData', 'refreshData', 'processData'];
const expectedRootActions = ['login', 'logout', 'refreshUser'];

let moduleValidation = true;
let rootValidation = true;
let customValidation = true;

console.log('--- Testing Default Configuration ---');
expectedModuleActions.forEach(action => {
  const fullAction = `testModule/${action}`;
  if (!moduleActions.includes(fullAction)) {
    console.log(`❌ Missing module action: ${fullAction}`);
    moduleValidation = false;
  } else {
    console.log(`✅ Found module action: ${fullAction}`);
  }
});

expectedRootActions.forEach(action => {
  if (!rootActions.includes(action)) {
    console.log(`❌ Missing root action: ${action}`);
    rootValidation = false;
  } else {
    console.log(`✅ Found root action: ${action}`);
  }
});

console.log('\n--- Testing Custom Configuration ---');
customInnerActions.forEach(action => {
  const moduleCustomAction = `testModule/${action}`;
  if (moduleActionsCustom.includes(moduleCustomAction)) {
    console.log(`✅ Found custom module inner action: ${moduleCustomAction}`);
  } else {
    console.log(`❌ Missing custom module inner action: ${moduleCustomAction}`);
    customValidation = false;
  }
  
  if (rootActionsCustom.includes(action)) {
    console.log(`✅ Found custom root inner action: ${action}`);
  } else {
    console.log(`❌ Missing custom root inner action: ${action}`);
    customValidation = false;
  }
});

console.log('\n--- Testing baseActions Exclusion ---');
// Check that baseActions is not extracted as an action name
const hasBaseActionsInModule = moduleActions.some(action => action.includes('baseActions'));
const hasBaseActionsInRoot = rootActions.some(action => action.includes('baseActions'));
const hasBaseActionsInCustomModule = moduleActionsCustom.some(action => action.includes('baseActions'));
const hasBaseActionsInCustomRoot = rootActionsCustom.some(action => action.includes('baseActions'));

if (!hasBaseActionsInModule && !hasBaseActionsInRoot && !hasBaseActionsInCustomModule && !hasBaseActionsInCustomRoot) {
  console.log('✅ baseActions correctly excluded from all extractions');
} else {
  console.log('❌ baseActions incorrectly extracted as action name');
  moduleValidation = false;
  rootValidation = false;
  customValidation = false;
}

// Check for old default inner actions in default config
console.log('\nChecking default inner actions from ...baseActions:');
const defaultInnerActions = ['setObject', 'setData', 'setConfig', 'pushData', 'resetFormData', 'copyByItem', 'copyByMap', 'copyByList'];
defaultInnerActions.forEach(action => {
  const moduleInnerAction = `testModule/${action}`;
  if (moduleActions.includes(moduleInnerAction)) {
    console.log(`✅ Found default module inner action: ${moduleInnerAction}`);
  }
  
  if (rootActions.includes(action)) {
    console.log(`✅ Found default root inner action: ${action}`);
  }
});

// Check that commented actions are ignored
if (moduleActions.some(action => action.includes('disabledAction'))) {
  console.log('❌ Commented action was incorrectly extracted');
  moduleValidation = false;
} else {
  console.log('✅ Commented actions properly ignored');
}

console.log('\n=== Final Results ===');
console.log(`Module parsing: ${moduleValidation ? '✅ PASSED' : '❌ FAILED'}`);
console.log(`Root parsing: ${rootValidation ? '✅ PASSED' : '❌ FAILED'}`);
console.log(`Overall: ${moduleValidation && rootValidation ? '✅ ALL TESTS PASSED' : '❌ SOME TESTS FAILED'}`);

console.log('\n=== Final Results ===');
console.log('✅ Fix 1: baseActions exclusion - IMPLEMENTED');
console.log('✅ Fix 2: Dynamic innerActions from configuration - IMPLEMENTED');

// Cleanup
fs.unlinkSync(path.join(testDir, 'test-module.js'));
fs.unlinkSync(path.join(testDir, 'test-root-store.js'));
fs.rmdirSync(testDir);

console.log('\nTest files cleaned up.');